<template>
  <div class="app-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline" @submit.native.prevent>
        <el-form-item label="使用场景">
          <el-select
            class="toolbar-lable-right"
            v-model="listQuery.q_pcMobile"
            placeholder="请选择" size="small">
            <el-option
              v-for="item in pcMobiles" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            class="toolbar-lable-right"
            v-model="listQuery.q_state"
            placeholder="请选择" size="small">
            <el-option
              v-for="item in states"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="this.getList">查询</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="button-table-margin">
        <el-button size="small" type="primary" @click="add" v-permission="['/admin/actgroupbanner/banner/create']">添加</el-button>
        <el-button size="small" type="primary" @click="edit" v-permission="['/admin/actgroupbanner/banner/update']">修改</el-button>
        <el-button size="small" type="primary" @click="del" v-permission="['/admin/actgroupbanner/banner/delete']">删除</el-button>
        <el-button size="small" type="primary" @click="gridUp" v-permission="['/admin/actgroupbanner/banner/up']">启用</el-button>
        <el-button size="small" type="primary" @click="gridDown" v-permission="['/admin/actgroupbanner/banner/down']">停用</el-button>
      </div>
      <el-table
        ref="singleTable"
        v-loading="listLoading"
        :data="dataList"
        border
        fit
        highlight-current-row
        @current-change="handleCurrentChange"
        style="width: 100%">
        <el-table-column type="index" align="center" width="50"></el-table-column>
        <el-table-column property="image" width="400" label="图片">
          <template slot-scope="scope">
            <img height="80px" :src="$imagePath + scope.row.image" alt="" />
          </template>
        </el-table-column>
        <el-table-column property="title" width="200" label="标题"></el-table-column>
        <el-table-column property="state" width="150" label="使用状态">
          <template slot-scope="scope">
            {{ codeBox.USE_YN[scope.row.state] }}
          </template>
        </el-table-column>
        <el-table-column property="pcMobile" width="150" label="使用场景">
          <template slot-scope="scope">
            {{ codeBox.PC_MOBILE[scope.row.pcMobile] }}
          </template>
        </el-table-column>
        <el-table-column property="linkUrl" width="200" label="链接地址"></el-table-column>
        <el-table-column property="startTime" width="200" label="开始时间"></el-table-column>
        <el-table-column property="endTime" width="200" label="结束时间"></el-table-column>
        <el-table-column property="orderNo" width="120" label="排序号"></el-table-column>
        <el-table-column property="createUserName" width="200" label="创建人"></el-table-column>
        <el-table-column property="createTime" width="200" label="创建时间"></el-table-column>
        <el-table-column property="updateUserName" width="200" label="修改人"></el-table-column>
        <el-table-column property="updateTime" width="200" label="修改时间"></el-table-column>
        <el-table-column fixed="right" label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button @click="gridUpRow(scope.row)" type="text" size="small">启用</el-button>
            <el-button @click="gridDownRow(scope.row)" type="text" size="small">停用</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

      <el-dialog title="添加" :visible.sync="dialogFormVisibleAdd" width="60%">
        <el-form ref="actGroupBannerCreate" :rules="rules" :model="actGroupBanner" label-position="right" label-width="100px" style="width: 700px;">
          <el-form-item label="标题" prop="title">
             <el-col :span="8"><el-input v-model="actGroupBanner.title" type="text" /></el-col>
          </el-form-item>
          <el-form-item label="链接地址" prop="linkUrl">
            <el-col :span="20"><el-input v-model="actGroupBanner.linkUrl" type="text"/></el-col>
          </el-form-item>
          <el-form-item label="排序" prop="orderNo">
            <el-input-number v-model="actGroupBanner.orderNo" :min="0" :max="99" :precision="0"></el-input-number>
            <span class="form-word-hint">序号越大越靠前显示</span>
          </el-form-item>
          <el-form-item label="应用场景" prop="pcMobile">
            <el-radio-group v-model="actGroupBanner.pcMobile">
              <el-radio v-for="item in pcMobiles" :key="item.value" :label="item.value">{{item.name}}</el-radio>
            </el-radio-group>
            <span class="form-word-hint">PC端针对电脑端，Mobile针对手机端</span>
          </el-form-item>
           <el-form-item label="展示时间" prop="yxkjdate">
              <el-date-picker
                 v-model="dateValue"
                 type="datetimerange"
                 range-separator="至"
                 start-placeholder="开始日期"
                 end-placeholder="结束日期"
                 value-format="yyyy-MM-dd HH:mm:ss"
                 @change="selectTime"
                 >
             </el-date-picker>
           </el-form-item>
          <el-form-item label="图片" prop="image">
            <el-upload
                    class="avatar-uploader"
                    :action="$imageUrl+'/uploadFileImage'"
                    :show-file-list="false"
                    :on-success="handleMasterSuccess"
                    :before-upload="beforeAvatarUpload">
              <img v-if="actGroupBanner.image" :src="$imagePath+actGroupBanner.image" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
           </el-form-item>
           <el-form-item>
              <el-col :span="22">
                <span class="form-word-hint">图片不能超过500KB，PC集合竞价图片最佳像素（或保持该比例）：宽740，高240；移动端集合竞价图片最佳像素（或保持该比例）：宽720，高350；</span>
              </el-col>
           </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibleAdd = false">
            取消
          </el-button>
          <el-button type="primary" @click="createSubmit()">
            提交
          </el-button>
        </div>
      </el-dialog>

      <el-dialog title="修改" :visible.sync="dialogFormVisibleEdit">
        <el-form ref="actGroupBanner" :rules="rules" :model="actGroupBanner" label-position="right" label-width="100px" style="width: 700px;">
          <el-form-item label="标题" prop="title">
             <el-col :span="8"><el-input v-model="actGroupBanner.title" type="text" /></el-col>
          </el-form-item>
          <el-form-item label="链接地址" prop="linkUrl">
            <el-col :span="20"><el-input v-model="actGroupBanner.linkUrl" type="text"/></el-col>
          </el-form-item>
          <el-form-item label="排序" prop="orderNo">
            <el-input-number v-model="actGroupBanner.orderNo" :min="0" :max="99" :precision="0"></el-input-number>
            <span class="form-word-hint">序号越大越靠前显示</span>
          </el-form-item>
          <el-form-item label="应用场景" prop="pcMobile">
            <el-radio-group v-model="actGroupBanner.pcMobile">
              <el-radio v-for="item in pcMobiles" :key="item.value" :label="item.value">{{item.name}}</el-radio>
            </el-radio-group>
            <span class="form-word-hint">PC端针对电脑端，Mobile针对手机端</span>
          </el-form-item>
           <el-form-item label="展示时间" prop="yxkjdate">
              <el-date-picker
                 v-model="dateValue"
                 type="datetimerange"
                 range-separator="至"
                 start-placeholder="开始日期"
                 end-placeholder="结束日期"
                 value-format="yyyy-MM-dd HH:mm:ss"
                 @change="selectTime"
                 >
             </el-date-picker>
           </el-form-item>
          <el-form-item label="图片" prop="image">
            <el-upload
                    class="avatar-uploader"
                    :action="$imageUrl+'/uploadFileImage'"
                    :show-file-list="false"
                    :on-success="handleMasterSuccess"
                    :before-upload="beforeAvatarUpload">
              <img v-if="actGroupBanner.image" :src="$imagePath+actGroupBanner.image" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
           </el-form-item>
           <el-form-item>
              <el-col :span="22">
                <span class="form-word-hint">图片不能超过500KB，PC集合竞价图片最佳像素（或保持该比例）：宽740，高240；移动端集合竞价图片最佳像素（或保持该比例）：宽720，高350；</span>
              </el-col>
           </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibleEdit = false">
            取消
          </el-button>
          <el-button type="primary" @click="updateSubmit()">
            提交
          </el-button>
        </div>
      </el-dialog>

  </div>
</template>

<script>
import { listActGroupBanner,createActGroupBanner,updateActGroupBanner,
    delActGroupBanner,auditYesActGroupBanner,auditNoActGroupBanner} from '@/api/promotion'
import Pagination from '@/components/Pagination'
import { Message } from 'element-ui'
import { getCodeManager,codeToArray, uploadFileImage} from '@/api/all'
export default {
  name: 'groupbannerlist',
  components: { Pagination },
  data() {
    return {
      currentRow: null,
      dataList: [],
      pcMobiles: [],
      states: [],
      dateValue:[],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        q_pcMobile: '',
        q_state: ''
      },
      dialogFormVisibleAdd: false,
      dialogFormVisibleEdit: false,
      actGroupBanner: {
        id: '',
        title: '',
        linkUrl: '',
        orderNo: 0,
        pcMobile: "1",
        image: '',
        yxkjdate: ''
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }],
        linkUrl: [{ required: true, message: '请输入链接地址', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 50 个字符', trigger: 'blur' }],
        orderNo: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
        yxkjdate: [{ required: true, message: '请选择日期', trigger: 'change' }],
        image: [{ required: true, message: '请上传图片', trigger: 'blur' }],
        pcMobile: [{ required: true, message: '请选择应用渠道', trigger: "change" }]
      }
    }
  },
  created() {
    this.getList()
    getCodeManager('USE_YN,YES_NO,PC_MOBILE', () => {
       this.pcMobiles = codeToArray('PC_MOBILE');
       this.states = codeToArray('USE_YN');
    })
  },
  methods:{
    handleCurrentChange(val) {
      // 选中当前行数据
      this.currentRow = val
    },
    // 获取列表数据
    getList() {
      this.listLoading = true
      listActGroupBanner(this.listQuery).then(response => {
        this.dataList = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      })
    },
    reset() {
      this.listQuery = {
        page: 1,
        limit: 20,
        q_pcMobile: '',
        q_state: ''
      }
      this.getList()
    },
    handleMasterSuccess(res, file) {
      const formData = new FormData()
      formData.append('type', 'mbanner')
      formData.append('imageFile', file.raw)
      uploadFileImage(formData).then(result => {
        console.log(result)
        if(result.data.success) {
          this.actGroupBanner.image = result.data.data;
        }
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size/1024 > 500;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG和PNG 格式!');
      }
      if (isLt2M) {
        this.$message.error('上传头像图片大小不能超过500K!');
      }
      return isJPG && !isLt2M;
    },
    selectTime(){
      this.actGroupBanner.yxkjdate = this.dateValue[0] + " - " + this.dateValue[1];
    },
    add() {
      this.actGroupBanner = {
        id: '',
        linkUrl: '',
        title: '',
        orderNo: 0,
        pcMobile: "1",
        image: '',
        yxkjdate: ''
      }
      this.dateValue = [];
      this.dialogFormVisibleAdd = true
      this.$nextTick(() => {
        this.$refs['actGroupBannerCreate'].clearValidate()
      })
    },
    createSubmit() {
      this.$refs['actGroupBannerCreate'].validate((valid) => {
        if (valid) {
          createActGroupBanner(this.actGroupBanner).then(res => {
            if(!res.data.success) {
              Message.error(res.data.message);
              return;
            }
            this.dialogFormVisibleAdd = false
            this.getList()
            Message.success('操作成功')
          })
        }
      })
    },
    edit() {
      if(this.currentRow == null) {
        Message.error('请选择一条记录')
        return
      }
      if(this.currentRow.state == 1) {
        Message.error('先停止使用，再进行修改')
        return
      }
      this.dateValue = []
      this.dateValue.push(this.currentRow.startTime)
      this.dateValue.push(this.currentRow.endTime)
      this.actGroupBanner = {
        id: this.currentRow.id,
        linkUrl: this.currentRow.linkUrl,
        title: this.currentRow.title,
        orderNo: this.currentRow.orderNo,
        pcMobile: '' + this.currentRow.pcMobile,
        image: this.currentRow.image,
        yxkjdate: this.currentRow.startTime + " - " + this.currentRow.endTime
      }
      this.dialogFormVisibleEdit = true
      this.$nextTick(() => {
        this.$refs['actGroupBanner'].clearValidate()
      })
    },
    updateSubmit() {
      this.$refs['actGroupBanner'].validate((valid) => {
        if (valid) {
          updateActGroupBanner(this.actGroupBanner).then(res => {
            if(!res.data.success) {
              Message.error(res.data.message);
              return;
            }
            this.dialogFormVisibleEdit = false
            this.getList()
            Message.success('操作成功')
          })
        }
      })
    },
    del() {
      if(this.currentRow.length == 0) {
        Message.error('请选择一条记录')
        return
      }
      if(this.currentRow.state == 1) {
        Message.error('使用中不能删除')
        return
      }
      this.$confirm('确定要删除吗？', '提示', {
        onfirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delActGroupBanner({id: this.currentRow.id}).then(res => {
          if(res.data.success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            });
          }
        })
      })
    },
    gridUp() {
      if(this.currentRow.length == 0) {
        Message.error('请选择一条记录')
        return
      }
      if(this.currentRow.state == 1) {
        Message.error('已经是启用状态，请勿重复操作')
        return
      }
      this.$confirm('确定启用吗？', '提示', {
        onfirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        auditYesActGroupBanner({id: this.currentRow.id}).then(res => {
          if(res.data.success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            });
          }
        })
      })
    },
    gridDown() {
      if(this.currentRow.length == 0) {
        Message.error('请选择一条记录')
        return
      }
      if(this.currentRow.state == 0) {
        Message.error('已经是停用状态，请勿重复操作')
        return
      }
      this.$confirm('确定停用吗？', '提示', {
        onfirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        auditNoActGroupBanner({id: this.currentRow.id}).then(res => {
          if(res.data.success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            });
          }
        })
      })
    },
    gridUpRow(currentRowSelect) {
      if(currentRowSelect.state == 1) {
        Message.error('已经是启用状态，请勿重复操作')
        return
      }
      this.$confirm('确定启用吗？', '提示', {
        onfirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        auditYesActGroupBanner({id: currentRowSelect.id}).then(res => {
          if(res.data.success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            });
          }
        })
      })
    },
    gridDownRow(currentRowSelect) {
      if(currentRowSelect.state == 0) {
        Message.error('已经是停用状态，请勿重复操作')
        return
      }
      this.$confirm('确定停用吗？', '提示', {
        onfirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        auditNoActGroupBanner({id: currentRowSelect.id}).then(res => {
          if(res.data.success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            });
          }
        })
      })
    }

  }
}
</script>
<style scoped>
/deep/ .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  /deep/ .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  /deep/ [class*=el-col-] {
    float: none;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    display: block;
    height: 150px;
  }
</style>
